#!/bin/bash
# webhook_service.sh
# Git Webhook服务的安装和管理脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # 无颜色

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否以root用户运行
if [ "$(id -u)" != "0" ]; then
    log_error "此脚本需要root权限运行。请使用sudo或以root身份运行。"
    exit 1
fi

# 设置变量
APP_DIR=$(dirname "$(dirname "$(readlink -f "$0")")")
WEBHOOK_SCRIPT="${APP_DIR}/scripts/git_webhook_server.py"
LOG_DIR="${APP_DIR}/logs"
SERVICE_NAME="git-webhook"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
WEBHOOK_PORT=${WEBHOOK_PORT:-8008}
WEBHOOK_HOST=${WEBHOOK_HOST:-0.0.0.0}
WEBHOOK_SECRET=${WEBHOOK_SECRET:-""}

# 确保日志目录存在
mkdir -p "${LOG_DIR}"

# 检查Flask是否已安装
check_dependencies() {
    log_info "检查依赖项..."
    if ! python3 -c "import flask" &>/dev/null; then
        log_info "安装Flask..."
        pip3 install flask || {
            log_error "安装Flask失败"
            exit 1
        }
    fi
    log_success "依赖项检查完成"
}

# 创建systemd服务文件
create_service() {
    log_info "创建systemd服务文件..."
    cat > "${SERVICE_FILE}" << EOF
[Unit]
Description=Git Webhook Server
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=${APP_DIR}
Environment="WEBHOOK_PORT=${WEBHOOK_PORT}"
Environment="WEBHOOK_HOST=${WEBHOOK_HOST}"
Environment="WEBHOOK_SECRET=${WEBHOOK_SECRET}"
ExecStart=/usr/bin/python3 ${WEBHOOK_SCRIPT}
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

    log_success "服务文件已创建: ${SERVICE_FILE}"
}

# 启动服务
start_service() {
    log_info "启动Git Webhook服务..."
    systemctl daemon-reload
    systemctl enable ${SERVICE_NAME}
    systemctl start ${SERVICE_NAME}
    
    # 检查服务状态
    if systemctl is-active --quiet ${SERVICE_NAME}; then
        log_success "Git Webhook服务已成功启动"
    else
        log_error "Git Webhook服务启动失败，请检查日志: journalctl -u ${SERVICE_NAME}"
        exit 1
    fi
}

# 停止服务
stop_service() {
    log_info "停止Git Webhook服务..."
    systemctl stop ${SERVICE_NAME}
    systemctl disable ${SERVICE_NAME}
    log_success "Git Webhook服务已停止"
}

# 重启服务
restart_service() {
    log_info "重启Git Webhook服务..."
    systemctl restart ${SERVICE_NAME}
    
    # 检查服务状态
    if systemctl is-active --quiet ${SERVICE_NAME}; then
        log_success "Git Webhook服务已成功重启"
    else
        log_error "Git Webhook服务重启失败，请检查日志: journalctl -u ${SERVICE_NAME}"
        exit 1
    fi
}

# 查看服务状态
status_service() {
    log_info "Git Webhook服务状态:"
    systemctl status ${SERVICE_NAME}
}

# 设置Webhook密钥
set_secret() {
    read -p "请输入Webhook密钥（留空则随机生成）: " user_secret
    if [ -z "$user_secret" ]; then
        # 生成随机密钥
        user_secret=$(openssl rand -hex 20)
        log_info "已生成随机密钥"
    fi
    
    # 更新服务文件中的密钥
    WEBHOOK_SECRET=${user_secret}
    create_service
    
    if [ -f "${SERVICE_FILE}" ]; then
        log_success "Webhook密钥已设置: ${WEBHOOK_SECRET}"
        log_info "请在Git仓库的Webhook设置中使用此密钥"
        
        # 如果服务正在运行，则需要重启
        if systemctl is-active --quiet ${SERVICE_NAME}; then
            restart_service
        fi
    else
        log_error "更新服务文件失败"
    fi
}

# 显示配置信息
show_config() {
    log_info "Git Webhook配置信息:"
    echo -e "服务名称: ${BLUE}${SERVICE_NAME}${NC}"
    echo -e "监听地址: ${BLUE}${WEBHOOK_HOST}:${WEBHOOK_PORT}${NC}"
    echo -e "Webhook URL: ${BLUE}http://<您的服务器IP>:${WEBHOOK_PORT}/webhook${NC}"
    echo -e "Webhook密钥: ${YELLOW}${WEBHOOK_SECRET:-'未设置'}${NC}"
    echo -e "服务文件: ${BLUE}${SERVICE_FILE}${NC}"
    echo -e "脚本位置: ${BLUE}${WEBHOOK_SCRIPT}${NC}"
    echo -e "日志目录: ${BLUE}${LOG_DIR}${NC}"
    echo ""
    
    # 显示服务状态
    if systemctl is-active --quiet ${SERVICE_NAME}; then
        echo -e "服务状态: ${GREEN}运行中${NC}"
    else
        echo -e "服务状态: ${RED}未运行${NC}"
    fi
}

# 显示帮助信息
show_help() {
    echo -e "${BLUE}Git Webhook 服务管理脚本${NC}"
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  install    安装并启动Webhook服务"
    echo "  start      启动Webhook服务"
    echo "  stop       停止Webhook服务"
    echo "  restart    重启Webhook服务"
    echo "  status     查看服务状态"
    echo "  secret     设置Webhook密钥"
    echo "  config     显示配置信息"
    echo "  help       显示此帮助信息"
    echo ""
}

# 安装服务
install_service() {
    log_info "开始安装Git Webhook服务..."
    
    # 检查webhook脚本是否存在
    if [ ! -f "${WEBHOOK_SCRIPT}" ]; then
        log_error "Webhook脚本不存在: ${WEBHOOK_SCRIPT}"
        exit 1
    fi
    
    # 检查依赖项
    check_dependencies
    
    # 询问配置
    read -p "请输入Webhook端口 [默认: 8008]: " port
    WEBHOOK_PORT=${port:-${WEBHOOK_PORT}}
    
    read -p "请输入监听地址 [默认: 0.0.0.0]: " host
    WEBHOOK_HOST=${host:-${WEBHOOK_HOST}}
    
    # 设置密钥
    read -p "是否设置Webhook密钥? (y/n) [默认: y]: " set_secret_choice
    set_secret_choice=${set_secret_choice:-y}
    if [[ "${set_secret_choice}" =~ ^[Yy]$ ]]; then
        read -p "请输入Webhook密钥（留空则随机生成）: " secret
        if [ -z "$secret" ]; then
            # 生成随机密钥
            secret=$(openssl rand -hex 20)
            log_info "已生成随机密钥: ${secret}"
        fi
        WEBHOOK_SECRET=${secret}
    fi
    
    # 创建服务文件
    create_service
    
    # 启动服务
    start_service
    
    # 显示配置信息
    show_config
    
    log_success "Git Webhook服务安装完成！"
    log_info "请在Git仓库的Webhook设置中配置以下URL和密钥："
    echo -e "URL: ${BLUE}http://<您的服务器IP>:${WEBHOOK_PORT}/webhook${NC}"
    echo -e "密钥: ${YELLOW}${WEBHOOK_SECRET}${NC}"
    echo -e "Content Type: ${BLUE}application/json${NC}"
}

# 主逻辑
case "$1" in
    install)
        install_service
        ;;
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    restart)
        restart_service
        ;;
    status)
        status_service
        ;;
    secret)
        set_secret
        ;;
    config)
        show_config
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        show_help
        exit 1
        ;;
esac

exit 0 